<template>
  <!-- 自动审核配置弹窗 -->
  <div>
    <el-dialog
      :title="dialogParam.title"
      v-model="model_value"
      :width="dialogParam.width"
      @close="cancelFn"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="110px"
      >
        <el-row>
          <el-col :span="24">
            <avue-crud
              ref="crudReview"
              :option="crudOptionReview"
              :data="formData.productInfoList"
              class="hide-required-asterisk"
            >
              <template #menu-left>
                <el-button type="primary" icon="Plus" @click="addReview"
                  >添加配置</el-button
                >
              </template>
              <template #menu="{ row, index }">
                <el-button
                  plain
                  icon="Delete"
                  link
                  @click="delRowReview(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <slot name="bottomBtn"></slot>
          <!-- <el-button @click="cancelUpload">取消</el-button> -->
          <el-button type="primary" @click="saveInvoice">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="ReviewConfig">
import { reactive, toRefs, ref } from 'vue'
import { isNum, maxDecimals } from '@/utils/validate'
import {
  listConfApprove,
  setConfApprove,
  delConfApprove
} from '@/api/indentManage/indent'
import { myToFixed } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import { parseTime } from '@/utils/ruoyi'
import {
  product_property //配置属性
} from '@/hooks/dict/order'

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  modelValue: {
    type: Boolean,
    require: true
  },
  dialogParam: {
    required: false,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})

// 操作类型
const operation_type = [
  { label: '手工录入', value: '1' },
  { label: '批量导入', value: '2' }
]

const dialogParam = ref({
  open: props.dialogParam.open,
  title: '自动审核配置',
  width: '1000px'
})
const formData = ref({
  productInfoList: []
})
const formRules = ref({})

const crudOptionReview = ref({
  header: true,
  menu: true,
  menuFixed: 'right',
  delBtn: false,
  editBtn: false,
  addBtn: false,
  addRowBtn: false,
  saveBtn: false,
  cancelBtn: false,
  cellBtn: false,
  // searchBtn: false,
  refreshBtn: false,
  columnBtn: false,
  menuWidth: 100,
  border: true,
  column: [
    {
      label: '操作类型',
      prop: 'operationType',
      type: 'select',
      clearable: false,
      class: 'w-full',
      dicData: operation_type,
      rules: [
        {
          required: true,
          message: '请输入操作类型',
          trigger: 'change'
        }
      ],
      cell: true
    },
    {
      label: '物料类型',
      prop: 'productType',
      type: 'select',
      class: 'w-full',
      clearable: false,
      dicData: product_property,
      rules: [
        {
          required: true,
          message: '请输入物料类型',
          trigger: 'change'
        }
      ],
      cell: true
    },
    {
      label: '金额上限',
      prop: 'price',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '130',
      controls: false,
      rules: [
        {
          required: false,
          message: '请输入金额上限',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            isNum(rule, value, callback)
          }
        }
      ],
      cell: true
    }
  ]
})
watch(
  () => props.modelValue,
  async val => {
    console.log('dialogParam.open==>', props.modelValue)
    if (props.modelValue) {
      dialogParam.value = { ...dialogParam.value, ...props.dialogParam }
      getlist()
    }
  },
  {
    // flush: 'post'
    immediate: true,
    deep: true
  }
)
const emit = defineEmits(['update:modelValue', 'close'])

const model_value = computed({
  get() {
    // console.log('props.modelValue==>', props.modelValue)
    dialogParam.value.open = props.modelValue
    return dialogParam.value.open
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const getlist = () => {
  listConfApprove().then(res => {
    formData.value.productInfoList = res.rows.map(item => {
      return {
        ...item,
        $cellEdit: true
      }
    })
  })
}

const saveInvoice = () => {
  proxy.$refs.form.validate(async (valid, msg) => {
    // 配置信息信息校验
    let errMsg = []
    let err = await proxy.$refs.crudReview.validateCellForm()
    if (err) {
      errMsg.push(`配置信息---${err[Object.keys(err)[0]][0].message}`)
    }
    if (msg) errMsg.unshift(`${msg[Object.keys(msg)[0]][0].message}`)
    if (valid && errMsg.length == 0) {
      setConfApprove(formData.value.productInfoList)
        .then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('保存成功')
            getlist()
          }
        })
        .catch(() => {
          getlist()
        })
      // console.log('formData==>', formData.value)
    } else {
      if (errMsg.length > 0) proxy.$modal.msgError(errMsg[0])
    }
  })
}

// 添加配置
function addReview() {
  formData.value.productInfoList.push({
    operationType: '',
    productType: '',
    // price: undefind,
    $cellEdit: true
  })
}

// 删除配置行
function delRowReview(row, index, done) {
  if (row.id) {
    proxy
      .$confirm('是否删除该配置', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        delConfApprove(row.id).then(() => {
          proxy.$message({
            type: 'success',
            message: '删除成功!'
          })
          getlist()
        })
        // formData.value.productInfoList.splice(index, 1)
        // proxy.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
      })
      .catch(() => {})
  } else {
    formData.value.productInfoList.splice(index, 1)
    proxy.$message({
      type: 'success',
      message: '删除成功!'
    })
  }
}

const clearValidate = () => {
  proxy.$refs.form.clearValidate()
}

// 取消
function cancelFn() {
  emit('close', false)
}
</script>
<style lang="scss" scoped>
.hide-required-asterisk {
  :deep(.w-full) {
    width: 100% !important;
  }
}
</style>
